package com.example.juc;

import java.util.concurrent.TimeUnit;

/**
 * 多人同时往卡上存钱
 * 线程不安全
 */
public class BankTest2 {
    public static int money = 0;

    public static void main(String[] args) throws InterruptedException {
        int [] data = new int[] {100, 200, 300};
        for (int i = 0; i < data.length; i++) {
            final int temp = i;
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(300);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                save(data[temp]);
            }).start();
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println("计算完成，最终存款总额: " + money);
    }

    public static synchronized void save(int m) {
        money += m;
    }
}
